<?php

namespace app\admin\controller\wdsxh;

use addons\wdsxh\library\Wxapp;
use app\admin\model\wdsxh\UserBelong;
use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 活动管理
 *
 * @icon fa fa-circle-o
 */
class Activity extends Backend
{

    /**
     * Activity模型对象
     * @var \app\admin\model\wdsxh\Activity
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\wdsxh\Activity;
        $this->view->assign("typeList", $this->model->getTypeList());
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("showList", $this->model->getShowList());
    }

    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {
                $row->cat;
                $row->append(['applytotal']);
                $row->applytotal = $this->applytotal($row['id']);

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    private function applytotal($activity_id)
    {
        return \app\admin\model\wdsxh\ActivityApply::where('activity_id', $activity_id)->where('status', '1')->count();
    }

    public function lists()
    {
        $row = $this->model->get($this->request->param('activity_id'));
        if (!$row) {
            $this->error('活动信息不存在');
        }
        $this->assignconfig('activity', $row);
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $apply = new \app\admin\model\wdsxh\ActivityApply();
            $status = ['1', '2', '3', '4'];
            if ($row->pay_type == '2') {
                $status = ['0', '1', '2', '3', '4'];
            }
            $list = $apply
                ->where($where)
                ->where('status', 'in', $status)
                ->where('activity_id', $this->request->param('activity_id'))
                ->order('createtime desc')
                ->paginate($limit);

            foreach ($list as $row) {
                $row->activity;
                $row->user;
                $row->member;
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);

                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = \app\admin\model\wdsxh\Activity::create($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->sendNewActivityNitice($result->toArray());
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        return $this->view->fetch();
    }

    private function sendNewActivityNitice($activity)
    {
        ini_set('max_execution_time', '0');
        try {
            $conf = (new \app\admin\model\wdsxh\Config())->where('id', 1)->find();
            $time = explode('-', $activity['time']);
            $startTime = strtotime(trim($time[0]));
            mb_internal_encoding("UTF-8");
            $data = [
                'thing1' => [
                    'value' => mb_substr($activity['title'], 0, 20),
                ],
                'thing2' => [
                    'value' => mb_substr($activity['brief'], 0, 20),
                ],
                'time5' => [
                    'value' => date('Y年m月d日 H:i', $startTime),
                ],
                'thing6' => [
                    'value' => mb_substr($activity['address'], 0, 20),
                ]
            ];

            $userIdArray = Db::name('user')->where('status', 'normal')->column('id');
            $userWhere['user_id'] = array('in', $userIdArray);
            $userLists = (new UserBelong())->where($userWhere)->field('openid')->select();
            $users = [];
            foreach ($userLists as $row) {
                $users[] = $row['openid'];
            }
            $res = Wxapp::subscribeMessage($conf['activity_new'], $users, '/pages/Functions/index', $data);
        } catch (\think\Exception $e) {
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    if ($params['status'] == '3') {
                        $this->finish($ids);
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /*
     * 活动结束处理
     */
    private function finish($activityId)
    {
        $map = array(
            'activity_id' => $activityId,
            'status' => '1',
        );
        \app\admin\model\wdsxh\ActivityApply::where($map)->update(array('status' => '4'));
        return true;
    }

    /*
     * 线下付款完成
     */
    /**
     * 通过
     */
    public function payment($ids = "")
    {
        $apply = \app\admin\model\wdsxh\ActivityApply::get($ids);
        if (!$apply) {
            $this->error('报名信息不存在');
        }
        $activity = $this->model->get($apply->activity_id);
        if(!$activity) {
            $this->error('活动信息不存在');
        }
        $population = $activity->population;
        $activity_apply_count = model('app\admin\model\wdsxh\ActivityApply')->where(['activity_id' => $apply->activity_id,'status' => '1'])->count();
        if($activity_apply_count >= $population) {
            $this->error('活动报名人数已满');
        }
        $apply->status = '1';
        $apply->save();
        // 活动人数已满，关闭报名
        if($activity_apply_count + 1 == $population) {
            $activity->status = '2';
            $apply->save();
        }

        // 活动报名成功通知
        try{
            $time=explode('-',$activity->time);
            $startTime=strtotime(trim($time[0]));
            $conf = (new \app\admin\model\wdsxh\Config())->where('id',1)->find();
            $user_id = $apply->user_id;
            $data=[
                'thing1'=>[
                    'value'=>$activity['title'],
                ],
                'amount3'=>[
                    'value'=>$apply['money'],
                ],
                'thing6'=>[
                    'value'=>$activity['address'],
                ],
                'date7'=>[
                    'value'=>date('Y年m月d日 H:i',$startTime),
                ],
                'phone_number8'=>[
                    'value'=>$activity['tel'],
                ]
            ];
            Wxapp::subscribeMessage($conf['activity_apply'],trim(wdsxh_get_openid($user_id)),'/pages/Functions/index',$data);
        }catch (\think\Exception $e){

        }

        $this->success('操作成功！');
    }
    /*
     * 线下退款完成
     */
    /**
     * 驳回
     */
    public function refund($ids = "")
    {
        $apply = \app\admin\model\wdsxh\ActivityApply::get($ids);
        if (!$apply) {
            $this->error('报名信息不存在');
        }
        $apply->status = '3';
        $apply->save();
        $this->success('操作成功！');
    }
}
